from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import UpdateView
from django.shortcuts import redirect, get_object_or_404
from django.contrib.auth.models import User

from braces.views import LoginRequiredMixin
from guardian.mixins import PermissionRequiredMixin
from userena.utils import signin_redirect, get_profile_model, get_user_model
from endless_pagination.decorators import page_template
from endless_pagination.views import AjaxListView

from .models import Profile
from .forms import AvatarForm

class ProfileAjaxListView(LoginRequiredMixin, AjaxListView):
    """
    Profile Ajax List View
    
    List user profile from the visible profiles
    
    :param template_name:
        String containing the base of the page to display the list
        
    :param page_template:
        String containing the name of template to display list of profile
    
    :param context_object_name:
        String containing the name of object to send to views
    
    """

    template_name = "profiles/profile_list_index.html"
    page_template = 'profiles/_profile_list_page.html'
    context_object_name = 'profile_list'
    
    def get_queryset(self):
        """
        Override AjaxListView get_queryset method
        Get the list of visible profiles for request user.
        """
        
        profile_model = get_profile_model()
        object_list = profile_model.objects.get_visible_profiles(self.request.user)
        object_list = object_list.exclude(user=self.request.user)
        
        return object_list


class ProfieAvatarUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
    """
    ProfieAvatarUpdateView
    Show Avatar form and let user to crop avatar to small picture.
    
    First User must logged in. Then 
    If a get_object() method is defined either manually or by including another mixin 
    (for example SingleObjectMixin) or self.object is defiend then the permission will be 
    tested against that specific instance.
    
    `get_object`:
        return Login profile
        
    `get_success_url`:
        return to user detail page
    """
    
    model = Profile
    form_class = AvatarForm
    template_name='profiles/avatar_form.html'
    
    # from PermissionRequiredMixin
    permission_required = 'profiles.change_profile'
    return_403 = True  # Returns 403 error page instead of redirecting user.
    
    def get_object(self):
        # Display contact information for specific contact_id
        profile = get_object_or_404(Profile, user__username=self.kwargs.get("username"))
        return profile
    
    def get_success_url(self):
        # Return to user detail
        return_url = reverse('avatar',kwargs={'username':self.kwargs.get("username")})
        return return_url
